<?php

/**
 * @Author: king
 * @Date:   2019-05-04 17:00:32
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-04 23:58:11
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use App\Models\Api\LanmeiCounselorProblem;
use AstroTool\Cache\ProblemAndAnswer;
use AstroTool\Cache\CacheManage;
use Cache;
class LanmeiCounselorGrabRecord extends Base
{
    protected $table = 'counselor_grab_record';

    /**
     * 获取用户今天抢答未完成的次数
     * @param $cid
     * @return int|string
     * @throws \Exception
     */
    public static function getUserGrabUnfinishNumByDay($cid)
    {
        $data = CacheManage::getInstance()->setCacheConfig('counselor_grab_unfinished', $cid . ':' . date('d'))
            ->getDataAndSet(function () use ($cid)
            {
                return self::getGrabUnfinishedByDayInData($cid);
            });

        return $data['num'];
    }

    /**
     * 咨询师今天 抢答未完成次数+1
     * @param $cid
     * @throws \Exception
     */
    public static function grabUnfinishedNumInc($cid)
    {
        CacheManage::getInstance()->setCacheConfig('counselor_grab_unfinished', $cid . ':' . date('d'))->setCacheInc('num');
    }

    /**
     * 获取用户今天抢答未完成的次数 通过数据库
     * @param $cid
     * @return array
     * @throws Exception
     */
    protected static function getGrabUnfinishedByDayInData($cid)
    {
        // 获取今天凌晨时间戳
        $startTime = strtotime(date('Y-m-d'));

        $unfinishedNum = self::where('c_id', $cid)->where('status', 2)->whereBetween('create_time', [$startTime, time()])->count();

        return ['num' => $unfinishedNum];
    }

    /**
     * 获取是否有 该问题 待完成的抢答记录
     * @param $cpId
     * @param $cid
     * @return int|string
     * @throws \Exception
     */
    public static function getPendingGrabAnswer($cpId, $cid)
    {   // 获取 抢答的 问题ID
        $problemId = self::getPendingGrabProblem($cid);

        if ($problemId == $cpId)
        {
            return true;
        } else
        {
            return false;
        }
    }

    /**
     * 设置咨询师抢答记录缓存
     * @param $cid
     * @param $cpId
     * @return mixed
     * @throws \Exception
     */
    public static function setCounselorGrabRecord($cid, $cpId)
    {
        // 更新缓存
        CacheManage::getInstance()->setCacheConfig('counselor_grab_record', $cid)
            ->setCache($cpId, 'details', false);

        return true;
    }

    /**
     * 获取咨询师 还没有完成的问题ID
     * @param $cid
     * @return mixed
     * @throws \Exception
     */
    public static function getPendingGrabProblem($cid)
    {
        $cpId = CacheManage::getInstance()->setCacheConfig('counselor_grab_record', $cid)->getCache();
        // $cpId = self::where('c_id', $cid)->where('status', 0)->order('id desc')->value('cp_id');

        return $cpId;
    }

    /**
     * 判断该问题是否存在抢答且待回答状态 的数据
     * @param $cpId
     * @return int|string
     * @throws Exception
     */
    public static function isPendingByProblem($cpId)
    {
        return self::where('cp_id', $cpId)->where('status', 0)->count();
    }

    /**
     * 抢答 回收
     * @param $id
     * @return bool
     * @throws \XznsTools\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public static function grabProblemCallBack($id)
    {
        $grabInfo = self::where('id', $id)->select('id','c_id','status','type','cp_id')->firstOrFail();

        if ($grabInfo['status'] > 0)
        {
            return true;
        }
        $grabInfo->status = 2;
        $grabInfo->save();
        $problemInfo = (new LanmeiCounselorProblem())->getProblemInfoById($grabInfo['cp_id'], 'problem_status,answer_people,counselor_mode,problem_type,order_id');
        // 判断当前问题状态
        if ($problemInfo['problem_status'] == 3)
        {   // 如果当前问题状态还是待回答状态 将问题抛回问题池
            ProblemAndAnswer::getInstance()->setCacheKey($grabInfo['type'])->lpushProblem($grabInfo['cp_id']);
        } elseif ($problemInfo['problem_status'] == 4 && $problemInfo['answer_people'] == 0)
        {   // 判断问题有没有人回答过；如果没有 且问题进入结算状态 问题关闭 -->全款退换
            (new LanmeiCounselorProblem())->problemClosed($grabInfo['cp_id'], $problemInfo['counselor_mode'], $problemInfo['problem_type'], $problemInfo['order_id']);
        }
        // 咨询师 取消抢单次数 +1
        LanmeiCounselorGrabRecord::grabUnfinishedNumInc($grabInfo['c_id']);

        return true;
    }

    /**
     * 抢单问题取消回答
     * @param $cpId
     * @param $cid
     * @return array
     * @throws \XznsTools\exception\ApiException
     * @throws \Exception
     */
    public static function grabCancel($cpId, $cid)
    {
        try
        {
            $recordInfo = self::where('c_id', $cid)->where('cp_id', $cpId)
                ->select('id','c_id','cp_id','status','type')
                ->first();

            if (!$recordInfo || $recordInfo['status'] > 0)
            {
                return ['status' => false, 'msg' => '状态异常'];
            }


            $recordInfo->update_time = time();
            $recordInfo->status = 2;
            $recordInfo->save();
        }
        catch (Exception $e)
        {
            return ['status' => false, 'msg' => $e->getMessage()];
        }
        // 获取问题信息
        $problemInfo = (new LanmeiCounselorProblem())->getProblemInfoById($cpId, 'problem_status');
        // 问题还在待回答状态
        if ($problemInfo['problem_status'] == 3)
        {
            // 将问题抛回问题池
            ProblemAndAnswer::getInstance()->setCacheKey($recordInfo['type'])->lpushProblem($cpId);
        }
        // 删除 抢单记录 缓存
        CacheManage::getInstance()->setCacheConfig('counselor_grab_record', $cid)->rmCache('details');
        // 咨询师 取消抢单次数 +1
        LanmeiCounselorGrabRecord::grabUnfinishedNumInc($cid);

        return ['status' => true, 'msg' => ''];
    }
}
